package com.eazy.lksy.controller;  
  
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eazy.lksy.model.User;
import com.eazy.lksy.service.UserService;
import com.eazy.lksy.utils.Bundle;
import com.eazy.lksy.utils.RequestUtils;
import com.eazy.lksy.utils.UserUtil;  
  

/**
 * @date 2016/1/28
 * @author jzx 
 * @desc 用户管理
 * http://spring.cndocs.tk/mvc.html
 * spring mvc 中文文档
 */
@Controller  
@RequestMapping("/user")  
public class UserController {  
  
	private static Log log = LogFactory.getLog(UserController.class);
	
    @Autowired  
    private UserService userService;  
    
    /**
     * 查询用户列表
     */
    @RequestMapping(value = "list" , method = RequestMethod.GET)  
    public ModelAndView selectUser() {  
    	ModelAndView modelAndView = new ModelAndView("user/user");
        modelAndView.addObject("userArray", userService.selectUser());
        return modelAndView;  
    }  
    
    /**
     * 添加用户
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String addUser(HttpServletRequest request) {
    	Map<String, String> maps = RequestUtils.actionRequest(request);
    	userService.add(new User(maps.get("name"),maps.get("password")));
    	return "redirect:/user/list";
    }
    
    /**
     * 修改用户 
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String updateUser(HttpServletRequest request) {
    	Map<String, String> maps = RequestUtils.actionRequest(request);
    	userService.update(new User(Bundle.convInt(maps.get("id")), maps.get("name"), maps.get("password")));
    	return "redirect:/user/list";
    }
    
    /**
     * 跳转到修改用户页面并获取用户ID
     */
    @RequestMapping(value = "toUpdate", method = RequestMethod.GET)
    public ModelAndView toUpdateUser(@RequestParam String id) {
    	ModelAndView modelAndView = new ModelAndView("/user/update");
    	User user = UserUtil.getCurrentUser();
    	modelAndView.addObject("user", user);
    	return modelAndView;
    }
    
    /**
     * 删除用户 
     */
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String deleteUser(@RequestParam String id) {
    	userService.delete(id);
    	return "redirect:/user/list";
    }
} 